package com.witmore.neutron.ai.web.wechat.controller;

import com.jk.common.response.ResponseResult;
import com.jk.mp.wx.config.WechatServiceProperties;
import com.jk.mp.wx.util.WechatSignatureUtils;
import com.jk.mp.wx.util.XmlUtils;
import com.witmore.neutron.ai.web.filter.GlobalAccountSession;
import com.witmore.neutron.ai.web.wechat.dto.CreateQrCodeParam;
import com.witmore.neutron.ai.web.wechat.dto.CreateQrCodeResponse;
import com.witmore.neutron.ai.web.wechat.dto.QrCodeResult;
import com.witmore.neutron.ai.web.wechat.dto.WechatCallbackMessage;
import com.witmore.neutron.ai.web.wechat.service.WechatCallbackService;
import com.witmore.neutron.ai.web.wechat.service.WechatForwardService;
import com.witmore.neutron.ai.web.wechat.service.WechatService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;

/**
 * 微信相关控制器
 * Author: 豆子高
 * Date: 2025/12/19
 */
@Slf4j
@RestController
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private WechatService wechatService;

    @Autowired
    private WechatCallbackService wechatCallbackService;

    @Autowired
    private WechatServiceProperties wechatProperties;

    @Autowired
    private WechatForwardService wechatForwardService;

    private final static String FR_DEFAULT = "default";

    /**
     * 生成带参数的二维码
     */
    @PostMapping("/create-qrcode")
    public ResponseResult<QrCodeResult> createQrCode(@RequestBody CreateQrCodeParam param) {
        if (!StringUtils.hasText(param.getFr())) {
            param.setFr(FR_DEFAULT);
        }
        param.setSceneValue(GlobalAccountSession.getUserInfo().getUserPhone() + "_" + param.getFr());
        try {
            // 生成唯一的场景值，可以包含业务参数
            String sceneStr = param.getSceneValue() + "_" + UUID.randomUUID().toString().replace("-", "").substring(0, 8);

            CreateQrCodeResponse response = wechatService.createQrCode(sceneStr, param.getExpireSeconds());

            if (response != null && StringUtils.hasText(response.getTicket())) {
                QrCodeResult result = new QrCodeResult();
                result.setTicket(response.getTicket());
                result.setUrl(response.getUrl());
                result.setSceneStr(sceneStr);
                result.setImageUrl(wechatService.getQrCodeImageUrl(response.getTicket()));
                result.setExpireSeconds(response.getExpireSeconds());

                return ResponseResult.success(result);
            } else {
                return ResponseResult.fail(500, "生成二维码失败");
            }
        } catch (Exception e) {
            log.error("生成微信二维码异常", e);
            return ResponseResult.fail(500, "生成二维码异常");
        }
    }

    /**
     * 微信服务器验证接口
     */
    @GetMapping("/callback")
    public String verify(@RequestParam("signature") String signature,
                         @RequestParam("timestamp") String timestamp,
                         @RequestParam("nonce") String nonce,
                         @RequestParam("echostr") String echostr) {
        log.info("微信服务器验证请求：signature={}, timestamp={}, nonce={}, echostr={}", signature, timestamp, nonce, echostr);

        // 验证签名
        boolean isValid = WechatSignatureUtils.checkSignature(wechatProperties.getToken(), signature, timestamp, nonce);

        if (isValid) {
            log.info("微信签名验证成功");
            return echostr;
        } else {
            log.warn("微信签名验证失败");
            return "error";
        }
    }

    /**
     * 微信消息回调接口
     */
    @PostMapping(value = "/callback", produces = "application/xml;charset=UTF-8")
    public String handleCallback(@RequestBody String xmlContent) {
        try {
            log.info("收到微信回调消息：{}", xmlContent);

            // 解析XML消息
            WechatCallbackMessage message = XmlUtils.parseXmlToObject(xmlContent, WechatCallbackMessage.class);

            // 处理回调消息
            String caM = wechatCallbackService.handleCallback(message);
            log.info("微信回调消息返回结果：{}", caM);

            // 异步转发到其他环境（不阻塞主流程）
            wechatForwardService.forwardToOtherEnvironments(xmlContent);

            return caM;
        } catch (Exception e) {
            log.error("处理微信回调消息异常", e);
            // 异常时必须返回success，避免微信重试和错误提示
            return "success";
        }
    }

}
